import { useEffect, useRef, useState } from 'react';

import { Box } from '@mui/material';

import { IAction } from 'state/action';
import { IMessage, INestedMessage, loadingState, messagesStatusState } from 'state/chat';
import { IMessageElement } from 'state/element';

import Messages from './MessageList';
import { useRecoilValue } from 'recoil';

interface Props {
  messages: IMessage[];
  elements: IMessageElement[];
  actions: IAction[];
  autoScroll?: boolean;
  setAutoScroll?: (autoScroll: boolean) => void;
}

// Nest messages based on parent id
function nestMessages(messages: IMessage[]): INestedMessage[] {
  const nestedMessages: INestedMessage[] = [];
  const lookup: Record<string, INestedMessage> = {};

  function addToParent(
    parentId: string | undefined,
    child: INestedMessage
  ): void {
    if (parentId) {
      const parent = lookup[parentId];
      if (!parent) return;
      if (!parent.subMessages) parent.subMessages = [];
      parent.subMessages.push(child);
    } else {
      nestedMessages.push(child);
    }
  }

  for (const message of messages) {
    const nestedMessage: INestedMessage = { ...message };
    if (message.id) lookup[message.id] = nestedMessage;
  }

  for (const message of messages) {
    if (!message.id) {
      nestedMessages.push({ ...message });
      continue;
    }

    const nestedMessage = lookup[message.id];
    if (!nestedMessage) continue;

    addToParent(message.parentId, nestedMessage);
  }

  return legacyNestMessages(nestedMessages);
}

// Nest messages based on deprecated indent parameter
function legacyNestMessages(messages: INestedMessage[]): INestedMessage[] {
  const nestedMessages: INestedMessage[] = [];
  const parentStack: INestedMessage[] = [];

  for (const message of messages) {
    const nestedMessage: INestedMessage = { ...message };
    const messageIndent = message.indent || 0;
    if (messageIndent && !message.authorIsUser && !message.waitForAnswer) {
      while (
        parentStack.length > 0 &&
        (parentStack[parentStack.length - 1].indent || 0) >= messageIndent
      ) {
        parentStack.pop();
      }

      const currentParent = parentStack[parentStack.length - 1];

      if (currentParent) {
        if (!currentParent.subMessages) {
          currentParent.subMessages = [];
        }
        currentParent.subMessages.push(nestedMessage);
      }
    } else {
      nestedMessages.push(nestedMessage);
    }

    parentStack.push(nestedMessage);
  }

  return nestedMessages;
}

const MessageContainer = ({
  messages,
  elements,
  actions,
  autoScroll,
  setAutoScroll
}: Props) => {
  const ref = useRef<HTMLDivElement>();
  const loading = useRecoilValue(loadingState);
  // @ts-ignore
  const filtered = 
    loading ? messages.filter(item => {
      return !item.content?.includes('也许你会对以下信息感兴趣') && !item.content?.includes('欢迎使用') && item.content !== 'Task stopped by the user.'
    }) as IMessage[] : messages.filter(item => {
      return !item.content?.includes('也许你会对以下信息感兴趣') && !item.content?.includes('欢迎使用') && item.content !== 'Task stopped by the user.'
    }) as IMessage[]
  const nestedMessages = nestMessages(filtered);
  const messagesStatus = useRecoilValue(messagesStatusState);
  

  const [ random, setRandom ] = useState('12345678')

  useEffect(() => {
    if (!ref.current || !autoScroll) {
      return;
    }
    ref.current.scrollTop = ref.current.scrollHeight;
  }, [messages, autoScroll, random, messagesStatus]);

  const handleScroll = () => {
    if (!ref.current || !setAutoScroll) return;
    const { scrollTop, scrollHeight, clientHeight } = ref.current;
    const atBottom = scrollTop + clientHeight >= scrollHeight - 30;
    setAutoScroll(atBottom);
  };
  return (
    <Box
      ref={ref}
      position="relative"
      display="flex"
      flexDirection="column"
      overflow="scroll"
      flexGrow={1}
      padding="20px 0 0 20px"
      onScroll={handleScroll}
      className="1111"
    >
      {/* 这里的两个div不能删，作为隔离的容器，用作思考中等等图片出现的辅助控制滚动条的 */}
      <div>
        <div className='overScroll'>
           <Messages
        indent={0}
        messages={nestedMessages}
        elements={elements}
        actions={actions}
        setRandom={setRandom}
        random = {random}
      />
        </div>
      </div>
    </Box>
  );
};

export default MessageContainer;
